<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--日历-->
      <el-col :span="4" :xs="24">
        <p><b>上课时间</b></p>
        <div class="my-calendar">
          <el-calendar v-model="queryParams.beginDate"></el-calendar>
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="40px">
          <el-form-item label="项目" prop="project">
            <el-input v-model="queryParams.project" placeholder="请输入项目" clearable
                      @keyup.enter.native="handleQuery"/>
          </el-form-item>
          <el-form-item label="场地" prop="roomId">
            <el-select v-model="queryParams.roomId" @change="getProgramList(null)" placeholder="请选择场地"
                       style="width: 250px">
              <el-option v-for="item in roomList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="教师" prop="teacher">
            <el-select v-model="queryParams.teacher" @change="getProgramList(null)" placeholder="请选择教师"
                       style="width: 250px">
              <el-option v-for="item in userList" :key="item.userId" :label="item.nickName"
                         :value="item.userId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                       v-hasPermi="['appoint:appoint:add']">新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                       v-hasPermi="['appoint:appoint:remove']">删除
            </el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList(true)"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="appointList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="项目" align="center" prop="project" width="120"/>
          <el-table-column label="场地" align="center" prop="roomName">
            <template slot-scope="scope">
              <el-popover placement="top" width="450" trigger="hover">
                <el-table :data="scope.row.pvAppointTimeList">
                  <el-table-column property="name" label="名称" width="100"></el-table-column>
                  <el-table-column label="时间范围">
                    <template slot-scope="scope1">
                      <el-tag slot="reference" effect="plain">{{ scope1.row.startTime }}</el-tag> ~
                      <el-tag slot="reference" type="warning" effect="plain">{{ scope1.row.endTime }}</el-tag>
                    </template>
                  </el-table-column>
                </el-table>
                <el-tag slot="reference" type="success" effect="plain">{{ scope.row.roomName }}</el-tag>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="实训项目" align="center" prop="trainingProgramName"/>
          <el-table-column label="教师" align="center" prop="teacher" width="100"/>
          <el-table-column label="开始时间" align="center" prop="beginDate" width="120">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.beginDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="结束时间" align="center" prop="endDate" width="120">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="容量(单个时间段)" align="center" prop="quantity" width="120"/>
          <el-table-column label="提前预约天数" align="center" prop="forwardDate"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                         v-hasPermi="['appoint:appoint:edit']">修改
              </el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                         v-hasPermi="['appoint:appoint:remove']">删除
              </el-button>
<!--              <el-button size="mini" type="text" icon="el-icon-message" @click="handleSms(scope.row)"-->
<!--                         v-hasPermi="['appoint:appoint:edit']">短信通知-->
<!--              </el-button>-->
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"  @pagination="getList"/>
      </el-col>
    </el-row>
    <!-- 添加或修改实训预约对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="场地" prop="roomId">
          <el-select v-model="form.roomId" @change="getProgramList" placeholder="请选择场地" style="width: 250px"
                     clearable>
            <el-option v-for="item in roomList" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="实训项目" prop="trainingprogramId">
          <el-select v-model="form.trainingprogramId" placeholder="请选择实训项目" @change="checkProgram"
                     style="width: 250px" clearable>
            <el-option v-for="item in programList" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="项目" prop="project">
          <el-input v-model="form.project" placeholder="请输入项目" style="width: 250px" clearable/>
        </el-form-item>
        <el-form-item label="教师" prop="teacher">
          <el-select v-model="form.teacher" allow-create filterable default-first-option placeholder="请选择教师(自定义回车确认)" style="width: 250px" clearable>
            <el-option v-for="item in userList" :key="item.nickName" :label="item.nickName" :value="item.nickName"/>
          </el-select>
        </el-form-item>
        <el-form-item label="上课日期" prop="dateRange">
          <el-date-picker v-model="form.dateRange" value-format="yyyy-MM-dd" type="daterange" align="right"
                          unlink-panels
                          range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                          :picker-options="pickerOptions"/>
        </el-form-item>
        <el-form-item label="上课时间">
          <el-table :data="pvAppointTimeList" ref="pvBookingTimeInfo" size="mini">
            <el-table-column label="名称" prop="name" width="150">
              <template slot-scope="scope">
                <el-input v-model="scope.row.name" placeholder="请输入名称" size="mini" clearable/>
              </template>
            </el-table-column>
            <el-table-column label="时间范围" prop="startTime" width="310">
              <template slot-scope="scope">
                <el-time-picker is-range start-placeholder="开始时间" end-placeholder="结束时间" @input="$forceUpdate()"
                                v-model="scope.row.time" value-format="HH:mm:ss" placeholder="时间范围" size="mini"
                                style="width: 300px"/>
              </template>
            </el-table-column>

            <el-table-column width="100">
              <template slot="header" slot-scope="scope">
                <el-button type="primary" @click="handleAddAppointTime" size="mini">添加一行</el-button>
              </template>
              <template slot-scope="scope">
                <el-button type="danger" icon="el-icon-delete" @click="handleDeleteAppointTime(scope.$index)" circle
                           size="mini"/>
              </template>
            </el-table-column>

          </el-table>
        </el-form-item>
        <el-form-item label="容量" prop="quantity">
          <el-input-number v-model="form.quantity" placeholder="请输入容量" style="width: 180px" clearable/>
        </el-form-item>
        <el-form-item label="提前预约天数" prop="forwardDate">
          <el-input-number v-model="form.forwardDate" placeholder="请输入提前预约天数" style="width: 180px" clearable/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 短信通知弹窗 -->
    <el-dialog title="发送短信通知" :visible.sync="sms.open" width="900px" append-to-body>
      <el-row>
        <el-col :span="12">
          <div style="width: 50%;position: relative;float: left;">
            <img :src="phoneSms" style="width: 300px;height: 600px" alt="">
            <p
              style="width: 200px;position:absolute;top:34%;left:56%;transform: translate(-50%, -50%);font-weight: bold;font-size: 15px;">
              【浦东新区妇幼保健中心】{{ sms.content }}</p>
          </div>
        </el-col>
        <el-col :span="10" style="float: left;margin-top: 200px">
          <el-form ref="form" :model="sms" label-width="120px">
            <el-form-item label="通知班级(可多选)" prop="classId">
              <el-select v-model="sms.classId" multiple placeholder="请选择班级">
                <el-option v-for="item in training_classList" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="开放时间" prop="time">
              <el-time-picker v-model="sms.time" @change="parseSmsFormat" value-format="HH:mm:ss" placeholder="选择开放时间"/>
            </el-form-item>
            <el-form-item>
              <el-button :type="sms.sended ? 'danger': 'primary'" icon="el-icon-message" @click="sendSms" :disabled="sms.sended" style="margin-top: 30px;width: 200px;height: 100px">
                {{ sms.sended ? '已发送' : '发送' }}
              </el-button>
            </el-form-item>
          </el-form>

        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import {listAppoint, delAppoint, addAppoint, updateAppoint, smsSend, smsSend_people_count} from "@/api/pv/appoint";
import {listTraining_class} from "@/api/pv/training_class";
import {listRoom} from "@/api/pv/room";
import {listProgram} from "@/api/pv/program";
import {listUser} from "@/api/system/userTeacher";
import {parseTime} from "@/utils/ruoyi";
import {copyObj, isEmptyStr, strFormat} from "@/utils/zzDouUtils/ObjUtil";
import {copyArr, isEmptyArr} from "@/utils/zzDouUtils/arrayUtil";
import phoneSms from "@/assets/images/phone_sms.png";
import {before} from "@/utils/zzDouUtils/dateUtil";

export default {
  name: "Appoint",
  data() {
    return {
      roomList: undefined,
      programList: undefined,
      userList: undefined,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 实训预约表格数据
      appointList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        project: null,
        roomId: null,
        deptId: null,
        trainingprogramId: null,
        classId: null,
        teacher: null,
        beginDate: null,
        endDate: null,
        dateRange: [],
        schoolTime: null,
        quantity: null,
        forwardDate: null,
      },
      // 预约时段表表格数据
      pvAppointTimeList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        roomId: [
          {required: true, message: "请选择场地", trigger: "blur"}
        ],
        trainingprogramId: [
          {required: true, message: "请选择实训项目", trigger: "blur"}
        ],
        // teacher: [
        //   { required: true, message: "请选择教师", trigger: "blur" }
        // ],
        dateRange: [
          {type: 'array', required: true, message: "请选择上课日期", trigger: "blur"}
        ],
        schoolTime: [
          {required: true, message: "请选择上课时间", trigger: "blur"}
        ],
        quantity: [
          {required: true, message: "请输入容量", trigger: "blur"}
        ],
        forwardDate: [
          {required: true, message: "请输入提前预约天数", trigger: "blur"}
        ],
      },
      training_classList: null,
      phoneSms: phoneSms,
      //短信通知
      sms: {
        open: false,
        bean: null,
        sended: false,//是否已经发送
        content: '',
        classId: [],
        time:'00:00:00'
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      }
    };
  },
  created() {
    this.getList();
    this.getRoomList();
    this.getTeacherList();
    this.getClassList();
  },
  methods: {
    parseTime,
    /** 查询用户列表 */
    getTeacherList() {
      listUser({}).then(response => {
          this.userList = response.rows;
        }
      );
    },
    /** 查询实训项目列表 */
    getProgramList(e) {
      this.roomList.forEach(item => {
        if (item.id == e) {
          this.form.quantity = item.quantity;
          this.form.forwardDate = item.forwardDate;
          return;
        }
      })
      //赋值
      listProgram({place: this.form.roomId}).then(response => {
        this.programList = response.rows;
      });
    },
    /** 查询培训班管理列表 */
    getClassList() {
      listTraining_class({pageSize: 100, pageNum: 1}).then(response => {
        this.training_classList = response.rows;
      });
    },
    checkProgram(e) {
      this.programList.forEach(item => {
        if (item.id == e) {
          this.form.project = item.name;
          this.pvAppointTimeList = [];
          for (let i = 0; i < item.room.bookingTime.pvBookingTimeInfoList.length; i++) {
            var obj = item.room.bookingTime.pvBookingTimeInfoList[i];
            this.pvAppointTimeList[i] = {name: obj.name};
            //时间选择器要使用 $set赋值
            this.$set(this.pvAppointTimeList[i], 'time', [parseTime(obj.startTime,'{h}:{i}:{s}'), parseTime(obj.endTime,'{h}:{i}:{s}')]);
          }
          return;
        }
      })
    },
    /** 查询场地管理列表 */
    getRoomList() {
      listRoom({}).then(response => {
        this.roomList = response.rows;
      });
    },
    /** 查询实训预约列表 */
    getList(refreshDate) {
      if (refreshDate) {
        this.queryParams.beginDate = null;
      }
      this.loading = true;
      listAppoint(this.queryParams).then(response => {
        this.appointList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        project: null,
        roomId: null,
        deptId: null,
        trainingprogramId: null,
        classId: null,
        teacher: null,
        beginDate: null,
        endDate: null,
        dateRange: [],
        schoolTime: [],
        quantity: null,
        forwardDate: null,
        reservedOne: null,
        reservedTwo: null,
        createTime: null
      };
      this.pvAppointTimeList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加实训预约";
    },
    /** 添加一行时间分段 */
    handleAddAppointTime() {
      const time = "00:00:00";
      this.pvAppointTimeList.push({name:null,time:[time,time]})
    },
    /** 删除一行时间分段 */
    handleDeleteAppointTime(index) {
      this.$delete(this.pvAppointTimeList,index);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log(row)
      this.reset();
      this.form = {...row};
      this.pvAppointTimeList = copyArr(row.pvAppointTimeList);
      for (let i = 0; i < this.pvAppointTimeList.length; i++) {
        //重新赋值
        this.$set(this.pvAppointTimeList[i],'time',[this.pvAppointTimeList[i].startTime, this.pvAppointTimeList[i].endTime]);
      }
      this.form.dateRange[0] = new Date(row.beginDate)
      this.form.dateRange[1] = new Date(row.endDate)
      this.getProgramList();
      this.open = true;
      this.title = "修改实训预约";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          //自定义校验
          if (isEmptyArr(this.pvAppointTimeList)) {
            this.$modal.msgWarning("至少需要一个时间段");
            return;
          } else {
            for (let i = 0; i < this.pvAppointTimeList.length; i++) {
              if (isEmptyStr(this.pvAppointTimeList[i].name)) {
                this.$modal.msgWarning(`时间段第${(i + 1)}行名称为空`);
                return;
              }
              if (isEmptyArr(this.pvAppointTimeList[i].time)) {
                this.$modal.msgWarning(`时间段第${(i + 1)}行时间为空`);
                return;
              }
              if (i !==0 && before(this.pvAppointTimeList[i].time[0],this.pvAppointTimeList[i-1].time[1])) {
                this.$modal.msgWarning(`时间段第${(i + 1)}行开始时间在上一行结束时间之后`);
                return;
              }
              //重新赋值
              this.pvAppointTimeList[i].startTime = this.pvAppointTimeList[i].time[0];
              this.pvAppointTimeList[i].endTime = this.pvAppointTimeList[i].time[1];
            }
          }
          //重新赋值
          this.form.pvAppointTimeList = this.pvAppointTimeList;
          this.form.beginDate = this.form.dateRange[0];
          this.form.endDate = this.form.dateRange[1];
          if (this.form.id != null) {
            updateAppoint(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAppoint(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除实训预约编号为"' + ids + '"的数据项？').then(function () {
        return delAppoint(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('appoint/appoint/export', {
        ...this.queryParams
      }, `appoint_${new Date().getTime()}.xlsx`)
    },
    /** 打开短信通知弹窗 */
    handleSms(row) {
      this.sms.bean = copyObj(row);
      this.parseSmsFormat();
      this.sms.sended = row.reservedTwo == '1';
      this.sms.open = true;
    },
    parseSmsFormat(){
      this.sms.content = strFormat('张三您好，${year}产褥期保健实训基地计划于${date}至${date1},每日${time}开放，请登录微信小程序“公卫处方权培训基地”，进行线上预约，并按期参加。', {
        year: parseTime(new Date(), '{y}'),
        date: parseTime(this.sms.bean.beginDate, '{y}-{m}-{d}'),
        date1: parseTime(this.sms.bean.endDate, '{y}-{m}-{d}'),
        time: this.sms.time
      });
    },
    /** 发送短信 */
    sendSms() {
      if (isEmptyArr(this.sms.classId)) {
        this.$modal.msgWarning("请选择班级")
        return;
      }
      smsSend_people_count(this.sms.classId,this.sms.time).then(response => {
        this.$confirm(`预计发送短信人数为 ${response.data} 人，是否确认发送`, '提示', {
          confirmButtonText: '发送',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true;
          smsSend(this.sms.bean.id, this.sms.classId,this.sms.time).then(response1 => {
            this.sms = {open: false, bean: null, sended: false, content: '', classId: []}
            this.$modal.msgSuccess("发送成功")
            this.loading = false;
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消成功'
          });
        });
      })
    }
  },
  watch: {
    'queryParams.beginDate': function (n, o) {
      this.queryParams.beginDate = this.parseTime(n, '{y}-{m}-{d}')
      this.getList();
    },
    'form.dateRange': function (n, o) {
      this.form.beginDate = n[0];
      this.form.endDate = n[1];
    }
  }
};
</script>
<style>
.my-calendar .el-calendar__header {
  width: 300px;
}

.my-calendar .el-button-group {
  width: 160px;
  float: right;
}

.my-calendar button {
  padding: 2px 7px;
}

.my-calendar .el-calendar__title {
  width: 100px;
  float: left;
  font-size: 13px;
}

.my-calendar .el-calendar__body {
  padding: 0;
}

.my-calendar .el-calendar-table .el-calendar-day {
  font-size: 14px;
  height: 34px;
}
</style>
